// ============================================================================
//
// Graph framework by Aurelien Moreau aurelien.moreau@gmail.com
// Modified by Pierre CHATEL chatelp@gmail.com
// Distributed under LGPL
// Copyright (C) Aurelien Moreau, 2008, 2009. All rights reserved
//
// ============================================================================

package com.thalesgroup.graphFramework.collections;

import java.io.Serializable;

public class Pair<U, V> implements Serializable, Comparable<Pair<U, V>> {

	private static final long serialVersionUID = -1004849195581675669L;

	final protected U first;

	final protected V second;

	public Pair(final U first, final V second) {
		this.first = first;
		this.second = second;
	}

	public U getFirst() {
		return first;
	}

	public V getSecond() {
		return second;
	}

	@Override
	public boolean equals(final Object obj) {
		if (obj == null) {
			return false;
		}
		if (this == obj) {
			return true;
		}
		if (obj instanceof Pair) {
			return first.equals(((Pair<?, ?>) obj).first)
					&& second.equals(((Pair<?, ?>) obj).second);
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		if (first == null && second == null) {
			return 0;
		} else if (first == null) {
			return second.hashCode();
		} else if (second == null) {
			return first.hashCode();
		} else {
			return first.hashCode() + second.hashCode();
		}
	}

	public static <U, V> Pair<U, V> new_(final U first, final V second) {
		return new Pair<U, V>(first, second);
	}

	@Override
	public String toString() {
		final StringBuffer buffer = new StringBuffer();
		buffer.append("(");
		buffer.append(first);
		buffer.append(",");
		buffer.append(second);
		buffer.append(")");
		return buffer.toString();
	}

	@SuppressWarnings("unchecked")
	public int compareTo(final Pair<U, V> o) {
		int result = ((Comparable<U>) first).compareTo(o.getFirst());
		if (result == 0) {
			result = ((Comparable<V>) second).compareTo(o.getSecond());
		}
		return result;
	}

}
